import { axiosNoConfig } from '../network/axios'

function postFile({ url, files, onUploadProgress }: any) {
  const formData = new FormData();
  formData.append('files', files);
  return axiosNoConfig({
    url,
    method: 'POST',
    data: formData,
    headers: {
      'Content-type': 'multipart/form-data',
      'token': localStorage.getItem('token')
    },
    onUploadProgress, // 上传进度回调函数 onUploadProgress(ev)
  });
}
/**
 * 
 * @param url 文件地址
 * @param fileName 文件名 xxx.mp4
 * @param callback progress
 * @returns 
 */
function downLoadFile(url: string, fileName: string, progressCallback?: any) {
  return new Promise((resolve, reject) => {
    axiosNoConfig({
      url,
      method: 'get',
      responseType: 'blob',
      onDownloadProgress: (evt: any) => {
        if (typeof progressCallback === 'function') {
          const percent = parseInt((evt.loaded / evt.total) * 100 + '')
          progressCallback(percent)
        }
      },
    })
      .then(res => {
        const blob = new Blob([res.data])
        const a = document.createElement('a')
        a.download = fileName
        a.href = URL.createObjectURL(blob)
        a.click()
        URL.revokeObjectURL(a.href)
        a.remove()
        resolve({})
      })
      .catch(err => {
        reject(err)
      })
  })
}

export {
  postFile,
  downLoadFile
}